import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mybase/base/tool/color/FFColor.dart';
import 'package:mybase/base/tool/globalMethod/FFScreenValue.dart';
import 'package:mybase/base/widget/layout/FFContainer.dart';

///弹窗布局
class FFWindow extends StatefulWidget {
  /// 返回的最好是 CustomScrollView，灵活性强
  /// 返回的列表要设置
  // shrinkWrap: true,
  // controller: controller,
  // physics: physics,
  Widget Function(
    BuildContext context,
    ScrollController? controller,
    ScrollPhysics? physics,
  ) builder;

  /// 约束最大高度
  BoxConstraints? constraints;

  /// 内边距
  EdgeInsetsGeometry? padding;

  /// 外边距
  EdgeInsetsGeometry? margin;

  /// 装饰
  Decoration? decoration;

  /// 宽
  double? width;

  FFWindow({
    super.key,
    required this.builder,
    this.constraints,
    this.width,
    this.padding,
    this.margin,
    this.decoration,
  });

  @override
  State<FFWindow> createState() => FFWindowState();
}

class FFWindowState extends State<FFWindow> {
  final ScrollController _scrollController = ScrollController();

  /// 用来发送事件 改变弹框高度的stream
  final StreamController<double> _streamController = StreamController<double>.broadcast();

  /// 列表弹起的正常高度
  double _totalHeight = 0;

  /// 记录手指按下的位置
  double _pointerDy = 0;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FFContainer(
      unconstrainedBox: true,
      width: widget.width ?? globalScreenWidth(context),
      padding: widget.padding ?? EdgeInsets.all(12.w),
      margin: widget.margin,
      decoration: widget.decoration ??
          BoxDecoration(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.w),
              topRight: Radius.circular(12.w),
              bottomLeft: Radius.circular(12.w),
              bottomRight: Radius.circular(12.w),
            ),
            color: Colors.black,
          ),
      constraints: widget.constraints ??
          BoxConstraints(
            minHeight: 20.w,
            maxHeight: globalScreenHeight(context) * 0.5,
          ),
      child: StreamBuilder<double>(
          stream: _streamController.stream,
          initialData: 0,
          builder: (context, snapshot) {
            double currentHeight = snapshot.data ?? 0;
            return AnimatedContainer(
              duration: const Duration(milliseconds: 30),
              child: Listener(
                onPointerDown: (event) {
                  // 触摸事件开始 手指开始接触屏幕
                  _pointerDy = event.position.dy + _scrollController.offset;
                },
                onPointerMove: (event) {
                  // 触摸事件过程 手指一直在屏幕上且发生距离滑动
                  if (_scrollController.offset != 0) {
                    // 只有列表滚动到顶部时才触发下拉动画效果
                    return;
                  }
                  double distance = event.position.dy - _pointerDy;
                  if (distance.abs() > 0) {
                    // 获取手指滑动的距离，计算弹框实时高度，并发送事件
                    double _currentHeight = _totalHeight - distance;
                    if (_currentHeight > _totalHeight) {
                      return;
                    }
                    _streamController.sink.add(_currentHeight);
                  }
                },
                onPointerUp: (event) {
                  // 触摸事件结束 手指离开屏幕
                  if (_scrollController.position.maxScrollExtent > 30.0 && currentHeight <= -_scrollController.position.maxScrollExtent) {
                    Navigator.pop(context);
                  } else {
                    _streamController.sink.add(_totalHeight);
                  }
                },
                child: widget.builder(
                  context,
                  _scrollController,
                  currentHeight != _totalHeight ? const NeverScrollableScrollPhysics() : const ClampingScrollPhysics(),
                ),
              ),
            );
          }),
    );
  }
}
